package edu.nju.login.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Servlet implementation class CookieServlet
 */
@WebServlet("/CookieServlet")
public class CookieServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CookieServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		handleRequest(request, response);

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		handleRequest(request, response);

	}
	
	private void handleRequest(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		HttpSession session = req.getSession(false);

       if(session==null){
    	   String loginValue = req.getParameter("login");
           boolean isLoginAction = (null == loginValue) ? false : true;

           if (isLoginAction) { // User is logging in

        		// create a session to show that we are logged in
                session = req.getSession(true);            
                session.setAttribute("login",loginValue);
				req.setAttribute("login",loginValue);
                displayLogoutPage(req, resp);
           }
           else{
        	// Display the login page. If the cookie exists, set login
               resp.sendRedirect(req.getContextPath() + "/Login");
           }
       }
       else{
    	   
    	   String loginValue = session.getAttribute("login").toString();
			req.setAttribute("login",loginValue);
           displayLogoutPage(req, resp);
           }
            
       
	}
    

	public void displayLogoutPage(HttpServletRequest req,
			HttpServletResponse res) throws IOException {
		ServletContext Context = getServletContext();
		int pageCounter = Integer.parseInt((String) Context
				.getAttribute("pageCounter"));

		res.setContentType("text/html");
		PrintWriter out = res.getWriter();
		out.println("<html><body>");
		out.println("<p>Welcome " + req.getAttribute("login") + "</p>");
		out.println("<form method='GET' action='"
				+ res.encodeURL(req.getContextPath() + "/Login") + "'>");
		out.println("Click <a href='" + res.encodeURL(req.getRequestURI())
				+ "'>here</a> to reload this page.<br>");
		out.println("</p>");
		out.println("<input type='submit' name='Logout' value='Logout'>");
		out.println("</form>");

		out.println("You are visitor number " + pageCounter);

		out.println("<p>Servlet is version @version@</p>");

		out.println("</body></html>");
	}


}
